package com.liujun.spring4.demo.aop.aopproblem.solve;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.OrderComparator;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Collections;
import java.util.List;

/**
 * @author liujun
 * @version 0.0.1
 * @date 2018/09/30
 */
@Component
public class SystemBootManager implements ApplicationListener<ContextRefreshedEvent> {

  private Logger log = LoggerFactory.getLogger(SystemBootManager.class);

  private List<SystemBootAddon> systemBootAddons = Collections.EMPTY_LIST;

  private boolean hasRunOnce = false;

  /**
   * 触发加载所有插件
   *
   * @param event
   */
  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    if (!hasRunOnce) {
      for (SystemBootAddon systemBootAddon : systemBootAddons) {
        systemBootAddon.onReady();
        if (log.isDebugEnabled()) {
          log.debug("执行插件:{}", systemBootAddon.getClass().getCanonicalName());
        }
      }
      hasRunOnce = true;
    } else {
      if (log.isDebugEnabled()) {
        log.debug("已经执行过容器启动插件集，本次忽略之");
      }
    }
  }

  @Autowired
  public void setSystemBootAddons(List<SystemBootAddon> systemBootAddons) {
    Assert.notEmpty(systemBootAddons);
    OrderComparator.sort(systemBootAddons);
    this.systemBootAddons = systemBootAddons;
  }
}
